package com.global.college.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.util.Log;

import com.google.gson.Gson;
import com.global.college.MainActivity;
import com.global.college.UserData;
import com.global.college.api.AuthURLs;
import com.global.college.api.BaseResponseModel;
import com.global.college.api.ProgressSubscriber;
import com.global.college.api.RequestClient;
import com.global.college.base.baselist.EventBusBean;
import com.global.college.constants.Constant;
import com.global.college.data.WeChatTokenBean;
import com.global.college.ui.activity.BindPhoneActivity;
import com.global.college.ui.bean.WechatLoginModel;
import com.global.college.utils.LogUtils;
import com.global.college.utils.StringUtils;
import com.global.college.utils.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 类描述：微信回调
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static final int GET_WX_TOKEN = 101;
    private static final int BIND_WX = 102;

    private IWXAPI api;
    private MyHandler handler;
    private String unionid, openid, accessToken;


    private class MyHandler extends Handler {

        public MyHandler() {
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_WX_TOKEN:
                    getWechatToken();
                    break;
                case BIND_WX:
                    bindWx();
                    break;
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, Constant.WECHAT_PAY_APP_ID, false);
        handler = new MyHandler();

        try {
            Intent intent = getIntent();
            api.handleIntent(intent, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                LogUtils.e("分享：" + "COMMAND_GETMESSAGE_FROM_WX");
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                LogUtils.e("分享：" + "COMMAND_SHOWMESSAGE_FROM_WX");
                break;
            case BaseResp.ErrCode.ERR_OK:
                LogUtils.e("微信登录：" + "ERR_OK");
                break;
            default:
                break;
        }
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        int result = 0;
        switch (resp.errCode) {

            case BaseResp.ErrCode.ERR_OK:
                LogUtils.e("分享：" + "ERR_OK:" + resp.getType());
                switch (resp.getType()) {
                    case 1:
                        //微信登录逻辑线
                        LogUtils.w("微信登录");
                        SendAuth.Resp newResp = (SendAuth.Resp) resp;
                        String code = newResp.code;
                        if (StringUtils.isNotEmpty(code, true)) {
                            String url = AuthURLs.WECHAT_TOKEN + "?appid=" + Constant.WECHAT_PAY_APP_ID + "&secret=" + Constant.WECHAT_SECRET + "&code=" + code + "&grant_type=authorization_code";
                            LogUtils.i("url" + url);
                            getWechatToken(url);
                        } else {
                            ToastUtils.showCenterToast("数据异常");
                        }

                        break;
                    case 2:
                        //微信分享线
                        LogUtils.w("微信分享");
                        break;
                    default:
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                LogUtils.e("分享：" + "ERR_USER_CANCEL");

                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                LogUtils.e("分享：" + "ERR_AUTH_DENIED");
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                LogUtils.e("分享：" + "ERR_UNSUPPORT");
                break;
            default:

                break;

        }
        finish();
    }

    /**
     * 获取微信授权信息
     *
     * @param url
     */
    public void getWechatToken(String url) {
        OkHttpClient client = new OkHttpClient();
        //创建一个Request
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        //发起异步请求，并加入回调
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败回调
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功回调
                final String string = response.body().string();
                final WeChatTokenBean weChatTokenBean = new Gson().fromJson(string, WeChatTokenBean.class);
                Log.i("WXEntryActivity--", string);
                openid = weChatTokenBean.getOpenid();
                unionid = weChatTokenBean.getUnionid();
                accessToken = weChatTokenBean.getAccess_token();
                Log.i("WXEntryActivity--", "openid:" + openid + ",unionid:" + unionid+",url="+url);
                Message msg = new Message();
                if (StringUtils.isEmpty(UserData.getInstance().getToken())) {//TOken为空时说明是首次登录绑定
                    msg.what = GET_WX_TOKEN;
                }
                else {//不为空时说明是已登录状态在设置页绑定
                    msg.what = BIND_WX;
                }
                handler.sendMessage(msg);
            }
        });

    }

    /**
     * 获取用户token，为空时说明用户不存在，跳转绑定手机号注册
     *
     * @param
     */
    public void getWechatToken() {
    }

    public void bindWx() {
        RequestClient.getInstance().bindWx(openid, unionid, accessToken).subscribe(new ProgressSubscriber<BaseResponseModel>(this, false) {
            @Override
            public void onNext(BaseResponseModel model) {
                ToastUtils.showToastShort("绑定成功");
                //EventBus.getDefault().post(new EventBusBean(0, Constant.EventBus.BIND_SUCCESS, ""));
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }

    public void onGetWechatUserSuccess(WechatLoginModel model) {
        if (StringUtils.isEmpty(model.getToken())) {
            startActivity(new Intent(this, BindPhoneActivity.class).putExtra("WxOpenId", openid).putExtra("WxUnionId", unionid).putExtra("accessToken", accessToken));
        } else {
            EventBus.getDefault().post(new EventBusBean(0, Constant.EventBus.WECHAT_LOGIN_SUCCESS, ""));
            UserData.getInstance().setToken(model.getToken());
            Intent intent = new Intent();
            intent.setClass(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

}